package com.fallsvc.re.javasesets.ebtree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int treeHeight(TreeNode root){
        if(root == null) return 0;
        int leftHeight = treeHeight(root.left);
        if(leftHeight < 0) return -1;
        int rightHeight = treeHeight(root.right);
        if(rightHeight != -1 && Math.abs(rightHeight - leftHeight) < 2) {
            return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
        }else {
            return -1;
        }

    }
    // 判断平衡树
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;

        return treeHeight(root) != -1;
    }


    // 判断是不是对称二叉树
    public boolean isSymmetric(TreeNode root) {
       if (root == null) return true;

       return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        //判断左右节点是否存在
        if(leftTree == null && rightTree == null) return true;
        if((leftTree != null && rightTree == null) ||
                (leftTree == null && rightTree != null))   return false;
        //有节点判断是否相等
        if(leftTree.val != rightTree.val) return false;
        //判断左右对称
        return isSymmetricChild(leftTree.left,rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
    }

    // 层序遍历  队列 + ArrayList<>()
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) return list;



        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()) {
            int size = q.size();
            List<Integer> c = new ArrayList<>();
            for(int i=0;i<size;i++) {
                TreeNode cur = q.poll();
                c.add(cur.val);
                if(cur.left != null)  q.offer(cur.left);
                if(cur.right != null) q.offer(cur.right);
            }
            list.add(c);
        }
        return list;
    }

}
